package com.chii.colorization.utils.connes;

import android.content.Context;

import com.alibaba.fastjson.JSONObject;
import com.chii.colorization.ui.activity.ColorizationActivity;
import com.chii.colorization.utils.SPUtil;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author chii
 */
public class OkHttpUtil {
    private static OkHttpUtil myOkHttp;
    private static OkHttpClient okHttpClient;
    public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("image/jpg");
    private static PersistentCookieStore persistentCookieStore;
    private static JSONObject token;
    public OkHttpUtil() {
        okHttpClient = new OkHttpClient.Builder()
                //设置连接超时时间
                .connectTimeout(20, TimeUnit.SECONDS)
                //设置读取超时时间
                .readTimeout(30, TimeUnit.SECONDS)
                .cookieJar(new CookiesManager(persistentCookieStore))
                .build();
    }

    public static OkHttpUtil getInstance(Context context) {
        if (myOkHttp == null) {
            persistentCookieStore = new PersistentCookieStore(context);
            myOkHttp = new OkHttpUtil();
        }
        //添加token
        JSONObject json = JSONObject.parseObject((String) SPUtil.get(context, "token", ""));
        if (json != null) {
            token = json;
        }
        return myOkHttp;
    }

    public HttpUrl.Builder initUrl(String url) {
        HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
        //添加token
        if (token != null) {
            httpBuilder.addQueryParameter("access_token", token.getString("access_token"));
        }
        return httpBuilder;
    }
    public static void delCookie(Context context) {
        if (persistentCookieStore == null) {
            persistentCookieStore = new PersistentCookieStore(context);
        }
        persistentCookieStore.removeAll();
    }


    public void get(String url, Map<String, String> params, MyCallback callback) {
        HttpUrl.Builder httpBuilder = initUrl(url);
        if (params != null) {
            for (Map.Entry<String, String> param : params.entrySet()) {
                httpBuilder.addQueryParameter(param.getKey(), param.getValue());
            }
        }
        Request request = new Request.Builder()
                .url(httpBuilder.build())
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.failed(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                callback.success(response.body().string());
            }
        });
    }

    public void delete(String url, Map<String, String> params, MyCallback callback) {
        HttpUrl.Builder httpBuilder = initUrl(url);
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        for (Map.Entry<String, String> param : params.entrySet()) {
            formBodyBuilder.add(param.getKey(), param.getValue());
        }
        FormBody formBody = formBodyBuilder.build();
        Request request = new Request.Builder()
                .url(httpBuilder.build())
                .delete(formBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.failed(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                callback.success(response.body().string());
            }
        });
    }
    public void post(String url, Map<String, String> params, MyCallback callback) {
        HttpUrl.Builder httpBuilder = initUrl(url);
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        for (Map.Entry<String, String> param : params.entrySet()) {
            formBodyBuilder.add(param.getKey(), param.getValue());
        }
        FormBody formBody = formBodyBuilder.build();
        Request request = new Request.Builder()
                .url(httpBuilder.build())
                .post(formBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.failed(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                callback.success(response.body().string());
            }
        });

    }

    public void postImage(String url,Map<String, String> params, File file, MyCallback callback) {
        HttpUrl.Builder httpBuilder = initUrl(url);
        //文件
        RequestBody fileBody = RequestBody.create(file, MEDIA_TYPE_MARKDOWN);
        MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder();
        requestBodyBuilder.setType(MultipartBody.FORM).addFormDataPart("file", file.getName(), fileBody);
        //添加其他参数
        for (Map.Entry<String, String> param : params.entrySet()) {
            requestBodyBuilder.addFormDataPart(param.getKey(), param.getValue());
        }
        MultipartBody requestBody = requestBodyBuilder.build();
        Request request = new Request.Builder()
                .url(httpBuilder.build())
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.failed(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                callback.success(response.body().string());
            }
        });
    }

    public interface MyCallback {

        void success(String s) throws IOException;

        void failed(IOException e);
    }
}
